package net.piggy.websocket.server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import java.util.Arrays;
import java.util.Locale;

public class WebSocketFrameHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.channel().close();
        cause.printStackTrace();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        ctx.channel().close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) {
        if (frame instanceof TextWebSocketFrame) {
            String request = ((TextWebSocketFrame) frame).text();
            ctx.channel().writeAndFlush(new TextWebSocketFrame("server: " + request.toUpperCase(Locale.US)));
        }else if(frame instanceof BinaryWebSocketFrame){
            ByteBuf buf = frame.content();
            byte[] array = new byte[buf.readableBytes()];
            buf.getBytes(buf.readerIndex(), array);
            System.out.println(Arrays.toString(array));

            buf.retain();
            String message = buf.toString(io.netty.util.CharsetUtil.UTF_8);
            System.out.println(message);
            buf.release();
        } else {
            String message = "unsupported frame type: " + frame.getClass().getName();
            throw new UnsupportedOperationException(message);
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
            WebSocketServerProtocolHandler.HandshakeComplete evt1 = (WebSocketServerProtocolHandler.HandshakeComplete) evt;
        }
        if (evt instanceof WebSocketServerProtocolHandler.ServerHandshakeStateEvent) {
            WebSocketServerProtocolHandler.ServerHandshakeStateEvent evt2 = (WebSocketServerProtocolHandler.ServerHandshakeStateEvent) evt;
        }
        super.userEventTriggered(ctx, evt);
    }

}
